/*
 * \brief  Core implementation of the IO_MEM session interface
 * \author Christian Helmuth
 * \date   2006-08-01
 */

/*
 * Copyright (C) 2006-2009 Christian Helmuth
 * Genode Labs, Feske & Helmuth Systementwicklung GbR
 *
 * This file is part of the Genode OS framework, which is distributed
 * under the terms of the GNU General Public License version 2.
 */

#include <util/string.h>
#include <util/arg_string.h>
#include <root/root.h>
#include <dataspace_component.h>
#include <io_mem_session_component.h>

using namespace Genode;


/* DEBUGGING */
static bool verbose = false;


Io_mem_session_component::Dataspace_attr
Io_mem_session_component::_prepare_io_mem(const char      *args,
                                          Range_allocator *ram_alloc)
{
	addr_t base = Arg_string::find_arg(args, "io_mem_base").ulong_value(0);
	size_t size = Arg_string::find_arg(args, "io_mem_size").ulong_value(0);

	Arg a = Arg_string::find_arg(args, "io_mem_cached");
	if (a.valid()) {
		bool cached = a.bool_value(0);
		PWRN("io_mem_cached not supported, want to set \"%s\"",
		     cached ? "on" : "off");
	}

	/* check for RAM collision */
	int ret;
	if ((ret = ram_alloc->remove_range(base, size))) {
		PERR("I/O memory [%lx,%lx) used by RAM allocator (%d)", base, base + size, ret);
		return Dataspace_attr(0, 0, 0);
	}

	/* allocate region */
	if (!_io_mem_alloc->alloc_addr(size, base)) {
		PERR("I/O memory [%lx,%lx) not available", base, base + size);
		return Dataspace_attr(0, 0, 0);
	}

	/* request local mapping */
	addr_t local_addr = _map_local(base, size);

	if (verbose)
		PDBG("I/O mem [%lx,%lx) => [%lx,%lx)",
		     base, base + size, local_addr, local_addr + size);

	return Dataspace_attr(size, local_addr, base);
}


Io_mem_session_component::Io_mem_session_component(Range_allocator   *io_mem_alloc,
                                                   Range_allocator   *ram_alloc,
                                                   Server_entrypoint *ds_ep,
                                                   const char        *args)
:
	_io_mem_alloc(io_mem_alloc),
	_ds(_prepare_io_mem(args, ram_alloc)),
	_ds_ep(ds_ep)
{
	if (!_ds.valid()) {
		PERR("Local MMIO mapping failed!");

		_ds_cap = Io_mem_dataspace_capability();
		throw Root::Invalid_args();
	}

	_ds_cap = Io_mem_dataspace_capability(_ds_ep->manage(&_ds));
}


Io_mem_session_component::~Io_mem_session_component()
{
	/* dissolve IO_MEM dataspace from service entry point */
	_ds_ep->dissolve(&_ds);

	/* flush local mapping of IO_MEM */
	_unmap_local(_ds.core_local_addr(), _ds.size());
	_ds.unmap();

	/* dataspace is removed from all RM sessions on destruction */

	/* free region in IO_MEM allocator */
	_io_mem_alloc->free(reinterpret_cast<void *>(_ds.phys_addr()));
}
